/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author
 */
public class XML {

    public static Document openDocument(String path) throws Exception {
        return openDocument(new File(path));
    }

    public static Document openDocument(File file) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        InputSource in = new InputSource(new InputStreamReader(new FileInputStream(file)));

        Document doc = builder.parse(in);
        return doc;
    }

    public static String getStr(Node context, String attrib) {
        String s = context.getAttributes().getNamedItem(attrib).getNodeValue();
        return s;
    }

    public static float getFloat(Node context, String attrib) {
        String s = context.getAttributes().getNamedItem(attrib).getNodeValue();
        return Float.parseFloat(s);
    }

    public static float[] getFloatArray(Node context, String... attribs) {
        float[] values = new float[attribs.length];
        for (int i = 0; i < attribs.length; ++i) {
            values[i] = getFloat(context, attribs[i]);
        }
        return values;
    }

    public static int getInt(Node context, String attrib) {
        String s = context.getAttributes().getNamedItem(attrib).getNodeValue();
        return Integer.parseInt(s);
    }

    public static NodeIterable iterate(NodeList list) {
        return new NodeIterable(list);
    }

    public static Document createDocument() throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.newDocument();
    }

    public static class NodeIterable implements Iterable<Node>, Iterator<Node> {

        NodeList list;
        int current;

        public NodeIterable(NodeList list) {
            this.list = list;
            this.current = 0;
        }

        @Override
        public Iterator<Node> iterator() {
            return this;
        }

        @Override
        public boolean hasNext() {
            return current < list.getLength();
        }

        @Override
        public Node next() {
            return list.item(current++);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}
